import { defineStore } from 'pinia'
import $axios from "../plugins/http"

export const useFriendPinia = defineStore('friend', {
  state: () => ({
    // 所有朋友的分组情况
    groups: {
      currentPage: 1,
      maxPage: 1,
      value: [] as Array<string>,
    },
    // 是否请求过获取所有好友
    isRequGetAllFriend: false,
    friends: new Map() as Map<string, Friend>,
    // 是否请求过通讯管理数据接口
    isRequFriendsManage: false,
    // 通讯录管理数据
    friendsManage: new Map([
      ['all', { noGroups: { isRequest: false, friends: new Map() as Map<string, Omit<OtherIdInfo, "userId">>, } }],
      ['disabledOtherLook', { noGroups: { isRequest: false, count: 0, friends: new Map() as Map<string, Omit<OtherIdInfo, "userId">>, } }],
      ['disabledSelfLook', { noGroups: { isRequest: false, count: 0, friends: new Map() as Map<string, Omit<OtherIdInfo, "userId">>, } }],
      ['groups', {
        groups: new Map() as Map<string, {
          isRequest: boolean;
          count: number;
          friends: Map<string, Omit<OtherIdInfo, "userId">>;
        }>
      }],
    ]) as Map<'all' | 'disabledOtherLook' | 'disabledSelfLook' | 'groups', FriendsManage>,
    friendsInfos: new Map() as Map<string, Omit<OtherIdInfo, 'userId'>>,
  }),
  getters: {
    friendsLen(): number {
      return [...this.friends.values()].reduce((beforeValue, currentValue) => beforeValue + currentValue.value.size, 0);
    },
  },
  actions: {
    // 获取用户的分组(第二页以上)
    getUserGroups(payload: { page: number }): Promise<{
      code: number;
      value: Array<string>;
    }> {
      let value: string[] = [];
      return new Promise<{ code: number; value: string[] }>((resolve, reject) => {
        $axios(
          ['/friend/getUserGroups', 'post', payload],
          ({ groups }) => {
            if (payload.page !== 0) this.groups.currentPage = payload.page
            else {
              this.groups.value.length && this.groups.value.splice(0);
              this.groups.currentPage = 1;
              this.groups.maxPage = 1;
            }
            this.groups.value.push(...groups);
            value = groups;
          },
        ).then((code: number) => resolve({
          code,
          value,
        })).catch(() => reject())
      })
    },
    // 请求某个好友的用户信息
    async getFriendInfos(payload: {
      selfId: string;
      otherId: string;
    }) {
      const { Base64 } = await import("js-base64");
      payload.otherId = Base64.encode(payload.otherId);
      payload.selfId = Base64.encode(payload.selfId);
      return await $axios(
        ['/friend/getFriendInfos', 'post', payload, true],
        ({ info }) => this.friendsInfos.set(info[0], info[1]),)
    },
    // 修改备注和分组
    async updateRemGroup(payload: {
      otherId: string;
      remark: string;
      group: string;
    }, oldGroup: string): Promise<{ code: number; initials: string }> {
      let initials: string = '';
      return new Promise<{ code: number; initials: string }>((resolve, reject) => {
        $axios(
          ['/friend/updateRemGroup', 'patch', payload],
          async ({ oldInitials, newInitials }) => {
            initials = newInitials;
            if (payload.group && !this.groups.value.includes(payload.group))
              this.groups.value.push(payload.group);
            const cacheInfo = this.friendsInfos.get(payload.otherId);
            if (cacheInfo) {
              if (cacheInfo.remark !== payload.remark) cacheInfo.remark = payload.remark;
              if (cacheInfo.group !== payload.group) cacheInfo.group = payload.group;
            }
            const { useMessagePinia } = await import('@/pinia/messages');
            const info = useMessagePinia().chatList.get(payload.otherId);
            info ? info.LatestMessInfo.remark = payload.remark : undefined;
            // 如果请求了所有好友的话
            if (this.isRequGetAllFriend) {
              const friends = this.friends.get(oldInitials)?.value!;
              const friendInfo = friends.get(payload.otherId)!;
              if (friendInfo.remark !== payload.remark) {
                friendInfo.remark = payload.remark;
                if (oldInitials !== newInitials) {
                  friends.delete(payload.otherId);
                  if (!friends.size) this.friends.delete(oldInitials);
                  if (this.friends.has(newInitials))
                    this.friends.get(newInitials)?.value.set(payload.otherId, friendInfo);
                  else {
                    const friendsArr = Array.from(this.friends);
                    if (newInitials !== '~') {
                      const index: number = friendsArr.findIndex(item => item[0] > newInitials);
                      friendsArr.splice(index, 0, [newInitials, { value: new Map().set(payload.otherId, friendInfo) }]);
                    } else friendsArr.push([newInitials, { value: new Map().set(payload.otherId, friendInfo) }]);
                    this.friends = new Map(friendsArr);
                  }
                }
              }
            }
            // 如果请求了通讯录数据的话
            if (this.isRequFriendsManage)
              for (const item of this.friendsManage.values()) {
                const newGroup = payload.group ? payload.group : '无分组';
                const olGroup = oldGroup ? oldGroup : '无分组';
                if (item?.noGroups) {
                  if (item.noGroups.isRequest && item.noGroups.friends.has(payload.otherId))
                    Object.assign(item.noGroups.friends.get(payload.otherId)!, {
                      remark: payload.remark,
                      group: payload.group,
                    })
                } else if (item.groups && item.groups.has(olGroup)) {
                  const data = item.groups.get(olGroup)!;
                  if (data.isRequest && data.friends.has(payload.otherId)) {
                    data.friends.get(payload.otherId)!.remark = payload.remark;
                    oldGroup !== payload.group && data.friends.delete(payload.otherId);
                  }
                  if (oldGroup !== payload.group) {
                    data.count--;
                    if (item.groups.has(newGroup)) {
                      const groupData = item.groups.get(newGroup)!;
                      groupData.count!++;
                      if (groupData.isRequest) groupData.isRequest = false;
                    } else {
                      item.groups.set(newGroup, {
                        isRequest: false,
                        count: 1,
                        friends: new Map([])
                      })
                    }
                  }
                }
              }
            const { useDynamicPinia } = await import('@/pinia/dynamic');
            const dynamicData = useDynamicPinia().dynamicDatas.value;
            const myDynamicData = useDynamicPinia().mySelfDynamicDatas.value;
            if (dynamicData.size)
              for (const value of dynamicData.values()) {
                if (value.userId === payload.otherId) value.remark = payload.remark;
                const thumbsData = value.thumbs.get(payload.otherId);
                if (thumbsData) thumbsData.remark = payload.remark;
                const commentData = value.comments;
                for (const { commenter, commenteder } of commentData.values()) {
                  if (commenter.userId === payload.otherId) commenter.remark = payload.remark;
                  if (commenteder?.userId === payload.otherId) commenteder.remark = payload.remark;
                }
              }
            if (myDynamicData.size)
              for (const value of myDynamicData.values()) {
                const thumbsData = value.thumbs.get(payload.otherId);
                if (thumbsData) thumbsData.remark = payload.remark;
                const commentData = value.comments;
                for (const { commenter, commenteder } of commentData.values()) {
                  if (commenter.userId === payload.otherId) commenter.remark = payload.remark;
                  if (commenteder?.userId === payload.otherId) commenteder.remark = payload.remark;
                }
              }
          }
        ).then(code => resolve({ code, initials })).catch(() => reject());
      })
    },
    /**
     * 修改朋友圈权限
     * @param permission - type值为disabledOtherLook代表只有不让对方看的权限发生变化,count为1则+1，否则-1
     * type值为disabledSelfLook代表只有不看对方的权限发生变化,count为1则+1，否则-1
     * type值为other时代表两种权限都改变了，此时count值便不再起作用了，则需要看changeType的值，如果该值为0，则
     * 两种都-1，为1则两种都+1，为2则是不让对方看+1，不看对方-1，为3则是不让对方看-1，不看对方+1
     */
    async updateMomPermission(
      payload: { otherId: string } & Permission,
      group: string,
      permission?: {
        type: "disabledOtherLook" | "disabledSelfLook" | "other";
        count: 1 | -1;
        changeType: 0 | 1 | 2 | 3;
      }
    ): Promise<number> {
      return await $axios(
        ['/friend/updateMomPermission', 'patch', payload],
        async () => {
          if (payload.disabledSelfLook) {
            const { useDynamicPinia } = await import('@/pinia/dynamic');
            const dynamicData = useDynamicPinia().dynamicDatas.value;
            if (dynamicData.size) {
              for (const [key, { userId }] of dynamicData)
                if (userId === payload.otherId) dynamicData.delete(key)
            }
          }
          const cacheInfo = this.friendsInfos.get(payload.otherId);
          if (cacheInfo) {
            if (cacheInfo.disabledOtherLook !== payload.disabledOtherLook)
              cacheInfo.disabledOtherLook = payload.disabledOtherLook;
            if (cacheInfo.disabledSelfLook !== payload.disabledSelfLook)
              cacheInfo.disabledSelfLook = payload.disabledSelfLook;
          }
          // 如果请求了通讯录数据的话
          if (this.isRequFriendsManage) {
            for (const [key, value] of this.friendsManage.entries()) {
              if (key === 'all') {
                value.noGroups?.isRequest &&
                  Object.assign(value.noGroups.friends.get(payload.otherId)!, {
                    disabledOtherLook: payload.disabledOtherLook,
                    disabledSelfLook: payload.disabledSelfLook,
                  })
              } else if (value?.noGroups) {
                value.noGroups.isRequest && value.noGroups.friends.has(payload.otherId) &&
                  Object.assign(value.noGroups.friends.get(payload.otherId)!, {
                    disabledOtherLook: payload.disabledOtherLook,
                    disabledSelfLook: payload.disabledSelfLook,
                  })
              } else if (value?.groups) {
                const datas = value.groups.get(group ? group : '无分组');
                datas && datas.isRequest &&
                  datas.friends.has(payload.otherId) &&
                  Object.assign(datas.friends.get(payload.otherId)!, {
                    disabledOtherLook: payload.disabledOtherLook,
                    disabledSelfLook: payload.disabledSelfLook,
                  })
              }
            }
            switch (permission?.type) {
              case 'disabledOtherLook':
              case 'disabledSelfLook':
                const noGroups = this.friendsManage.get(permission.type)!.noGroups!;
                noGroups.count! += permission.count;
                if (noGroups?.isRequest) {
                  if (permission.count === 1) noGroups.isRequest = false;
                  else if (noGroups.friends.has(payload.otherId))
                    noGroups.friends.delete(payload.otherId)
                }
                break;
              case 'other': {
                const otherData = this.friendsManage.get('disabledOtherLook')!.noGroups!;
                const selfData = this.friendsManage.get('disabledSelfLook')!.noGroups!;
                switch (permission.changeType) {
                  case 0: {
                    otherData.count! --;
                    selfData.count! --;
                    otherData.isRequest && otherData.friends.has(payload.otherId) &&
                      otherData.friends.delete(payload.otherId);
                    selfData.isRequest && selfData.friends.has(payload.otherId) &&
                      selfData.friends.delete(payload.otherId);
                    break;
                  }
                  case 1: {
                    otherData.count! ++;
                    selfData.count! ++;
                    otherData.isRequest ? otherData.isRequest = false : undefined;
                    selfData.isRequest ? selfData.isRequest = false : undefined;
                    break;
                  }
                  case 2: {
                    otherData.count! ++;
                    otherData.isRequest ? otherData.isRequest = false : undefined;
                    selfData.count! --;
                    selfData.isRequest && selfData.friends.has(payload.otherId) &&
                      selfData.friends.delete(payload.otherId);
                    break;
                  }
                  case 3: {
                    otherData.count! --;
                    otherData.isRequest && otherData.friends.has(payload.otherId) &&
                      otherData.friends.delete(payload.otherId);
                    selfData.count! ++;
                    selfData.isRequest ? selfData.isRequest = false : undefined;
                    break;
                  }
                }; break;
              }
            }
          }
        },
      )
    },
    // 获取所有的好友
    getAllFriends(payload: { slefId: string; filter?: boolean }): Promise<{
      code: number;
      friendsData: Map<string, Friend>;
    }> {
      return new Promise<{ code: number; friendsData: Map<string, Friend> }>((resolve, reject) => {
        let friendsData: Map<string, Friend> = new Map();
        $axios(
          ['/friend/getFriends', 'get', payload, true],
          (data) => {
            const datas: Map<string, Friend> = new Map(data);
            friendsData = datas;
            if (!payload.filter && !this.isRequGetAllFriend) {
              for (const [key, value] of datas.entries())
                this.friends.set(key, {
                  value: new Map(value.value)
                });
              this.isRequGetAllFriend = true;
            }
          },
        ).then(code => resolve({ code, friendsData })).catch(() => reject())
      })
    },
    // 删除好友
    async deleteFriend(
      payload: {
        selfId: string;
        otherIds: Array<string>;
        callback?: (...arg: any[]) => any;
      },
    ): Promise<number> {
      return await $axios(
        [
          '/friend/delete',
          'post',
          {
            selfId: payload.selfId,
            otherIds: payload.otherIds,
          },
        ],
        async ({ initials, infos }) => {
          const { useMessagePinia } = await import("@/pinia/messages");
          const { useDynamicPinia } = await import("@/pinia/dynamic");
          const messageStore = useMessagePinia();
          const dynamicData = useDynamicPinia().dynamicDatas.value;
          payload?.callback && payload.callback();
          setTimeout(() => {
            // 删除消息记录
            payload.otherIds.forEach(otherId => {
              if (messageStore.chatList.has(otherId)) messageStore.chatList.delete(otherId)
            });
            // 删除好友列表的数据
            for (let i = 0; i < payload.otherIds.length; i++) {
              if (this.friendsInfos.has(payload.otherIds[i]))
                this.friendsInfos.delete(payload.otherIds[i]);
              const friends = this.friends.get(initials[i])?.value!;
              friends.delete(payload.otherIds[i]);
              if (!friends.size) this.friends.delete(initials[i]);
              // 删除通讯管理的数据
              if (this.isRequFriendsManage) {
                for (const [key, value] of this.friendsManage) {
                  if (key === 'all')
                    value.noGroups?.isRequest && value.noGroups.friends.delete(payload.otherIds[i]);
                  else if (value?.noGroups) {
                    if (key === 'disabledOtherLook') {
                      if (infos[i].disabledOtherLook) {
                        value.noGroups.count!--;
                        value.noGroups.isRequest && value.noGroups.friends.has(payload.otherIds[i]) &&
                          value.noGroups.friends.delete(payload.otherIds[i]);
                      }
                    } else if (infos[i].disabledSelfLook) {
                      value.noGroups.count!--;
                      value.noGroups.isRequest && value.noGroups.friends.has(payload.otherIds[i]) &&
                        value.noGroups.friends.delete(payload.otherIds[i]);
                    }
                  } else if (value?.groups && value.groups.has(infos[i].group)) {
                    const friendsData = value.groups.get(infos[i].group)!;
                    friendsData.count--;
                    friendsData.isRequest && friendsData.friends.has(payload.otherIds[i]) &&
                      friendsData.friends.delete(payload.otherIds[i])
                  }
                }
              }
            };
            if (dynamicData.size)
              for (const [key, value] of dynamicData)
                if (payload.otherIds.includes(value.userId)) dynamicData.delete(key);
          })
        },
      )
    },
    // 获取通讯录管理
    async getFriendsManage(): Promise<number> {
      return await $axios(
        ['/friend/getFriendsManage', 'get'],
        ({
          disabledOtherLookCount,
          disabledSelfLookCount,
          groups,
        }) => {
          this.friendsManage.get('disabledOtherLook')!.noGroups!.count = disabledOtherLookCount;
          this.friendsManage.get('disabledSelfLook')!.noGroups!.count = disabledSelfLookCount;
          this.friendsManage.get('groups')!.groups = new Map(groups);
          if (this.groups.value.length !== groups.length - 1) {
            this.groups.currentPage = 1;
            this.groups.maxPage = 1;
            this.groups.value.splice(0);
            for (const group of groups)
              group[0] !== '无分组' && this.groups.value.push(group[0])
          }
          this.isRequFriendsManage = true;
        },
      )
    },
    // 获取对应分组下的好友列表数据
    async getTagFriends(payload: {
      title: 'all' |
      'disabledOtherLook' |
      'disabledSelfLook' |
      'groups';
      type: string;
    }): Promise<number> {
      return await $axios(
        ['/friend/getTagFriends', 'post', payload, true],
        (friends: Array<[string, Pick<
          OtherIdInfo,
          "remark" | "nickName" | "avatar" | "disabledOtherLook" | "disabledSelfLook" | "group"
        >]>) => {
          for (const [userId, { nickName }] of friends)
            if (this.friendsInfos.has(userId)) {
              const data = this.friendsInfos.get(userId)!;
              if (data.nickName !== nickName) data.nickName = nickName;
            }
          switch (payload.title) {
            case 'all':
            case 'disabledOtherLook':
            case 'disabledSelfLook':
              const friendsData = this.friendsManage.get(payload.title)?.noGroups!;
              Object.assign(friendsData, {
                friends: new Map(friends),
                isRequest: true,
              });
              if (payload.title === 'all') {
                if (this.friendsLen !== friends.length)
                  for (const [initial, item] of this.friends.entries()) {
                    for (const key of item.value.keys())
                      if (!friendsData.friends.has(key)) item.value.delete(key);
                    !item.value.size && this.friends.delete(initial);
                  }
              }
              else if (friendsData.count !== friends.length) friendsData.count = friends.length;
              break;
            case 'groups': {
              const data = this.friendsManage.get(payload.title)?.groups!;
              if (data.has(payload.type)) {
                const friendsList = data.get(payload.type)!;
                Object.assign(friendsList, {
                  isRequest: true,
                  friends: new Map(friends),
                });
                if (friends.length !== friendsList.count)
                  friendsList.count = friends.length;
              }
            }; break;
          }
        },
      )
    },
    // 设置分组，可能为多人
    async updateGroup(payload: {
      selfId: string;
      otherIds: Array<string>;
      group: string;
    }, oldGroup?: string): Promise<number> {
      return await $axios(
        ['/friend/group/updateGroup', 'patch', { ...payload, type: 0 }],
        () => {
          if (payload.group && !this.groups.value.includes(payload.group))
            this.groups.value.push(payload.group);
          for (const otherId of payload.otherIds) {
            const cacheInfo = this.friendsInfos.get(otherId);
            cacheInfo ? cacheInfo.group = payload.group : undefined;
            // 如果// 如果请求了通讯录数据的话
            if (this.isRequFriendsManage) {
              for (const item of this.friendsManage.values()) {
                const newGroup = payload.group ? payload.group : '无分组';
                const olGroup = oldGroup ? oldGroup : '无分组';
                if (item?.noGroups) {
                  if (item.noGroups.isRequest && item.noGroups.friends.has(otherId))
                    item.noGroups.friends.get(otherId)!.group = payload.group;
                } else if (item.groups && item.groups.has(olGroup)) {
                  const data = item.groups.get(olGroup)!;
                  if (data.isRequest && data.friends.has(otherId) && oldGroup !== payload.group)
                    data.friends.delete(otherId);
                  if (oldGroup !== payload.group) {
                    data.count--;
                    if (item.groups.has(newGroup)) {
                      const groupData = item.groups.get(newGroup)!;
                      groupData.count!++;
                      if (groupData.isRequest) groupData.isRequest = false;
                    } else {
                      item.groups.set(newGroup, {
                        isRequest: false,
                        count: 1,
                        friends: new Map([])
                      })
                    }
                  }
                }
              }
            }
          }
        },
      )
    },
    // 移出分组
    async moveGroup(payload: {
      selfId: string;
      group: string;
      otherIds: Array<string>;
    }): Promise<number> {
      return await $axios(
        ['/friend/group/updateGroup', 'patch', {
          selfId: payload.selfId,
          otherIds: payload.otherIds,
          type: 1,
        }],
        () => {
          for (const otherId of payload.otherIds) {
            const cacheInfo = this.friendsInfos.get(otherId);
            cacheInfo ? cacheInfo.group = '' : undefined;
            // 如果// 如果请求了通讯录数据的话
            if (this.isRequFriendsManage) {
              for (const item of this.friendsManage.values()) {
                if (item?.noGroups) {
                  if (item.noGroups.isRequest && item.noGroups.friends.has(otherId))
                    item.noGroups.friends.get(otherId)!.group = '';
                } else if (item.groups && item.groups.has(payload.group)) {
                  const data = item.groups.get(payload.group)!;
                  const noGroupData = item.groups.get('无分组')!;
                  if (data.isRequest) {
                    if (data.friends.has(otherId)) {
                      const friendData = data.friends.get(otherId)!;
                      friendData.group = '';
                      noGroupData.isRequest ? noGroupData.friends.set(otherId, friendData) : undefined;
                      data.friends.delete(otherId);
                    }
                  } else if (noGroupData.isRequest) noGroupData.isRequest = false;
                  data.count--;
                  noGroupData.count++;
                }
              }
            }
          }
        },
      )
    },
    // 创建新的分组
    async createGroup(payload: {
      selfId: string;
      group: string;
    }): Promise<number> {
      return await $axios(
        ['/friend/group/createGroup', 'post', payload],
        () => {
          !this.groups.value.includes(payload.group) && this.groups.value.push(payload.group);
          this.friendsManage.get('groups')?.groups?.set(payload.group, {
            isRequest: true,
            count: 0,
            friends: new Map(),
          });
        },
      )
    },
    // 请求无分组的数据
    getNoGroupData(): Promise<{
      code: number; friendsData: Array<{
        userId: string;
        avatar: string;
        remark: string
      }>;
    }> {
      let friendsData: Array<{
        avatar: string;
        remark: string;
        userId: string;
      }>;
      return new Promise<{
        code: number; friendsData: Array<{
          userId: string;
          avatar: string;
          remark: string;
        }>
      }>((resolve, reject) => {
        $axios(
          ['/friend/getNoGroupData', 'get'],
          (data) => friendsData = data
        ).then(code => resolve({ code, friendsData })).catch(() => reject());
      })
    },
    // 修改分组名
    async modifyGroupName(payload: {
      selfId: string;
      oldGroup: string;
      newGroup: string;
    }): Promise<number> {
      return await $axios(
        ['/friend/group/modifyGroupName', 'patch', payload],
        ({ otherIds }) => {
          if (this.groups.value.includes(payload.oldGroup)) {
            const index: number = this.groups.value.findIndex(item => item === payload.oldGroup);
            this.groups.value[index] = payload.newGroup;
          }
          if (otherIds.length) {
            for (let i = 0; i < otherIds.length; i++) {
              const cacheInfo = this.friendsInfos.get(otherIds[i]);
              cacheInfo ? cacheInfo.group = payload.newGroup : undefined;

              const strs = ['all', 'disabledOtherLook', 'disabledSelfLook'] as const;
              for (const str of strs) {
                const friendsData = this.friendsManage.get(str)?.noGroups;
                if (friendsData?.isRequest && friendsData.friends.has(otherIds[i]))
                  friendsData.friends.get(otherIds[i])!.group = payload.newGroup;
              }
            }
          }
          const groupsAllData = this.friendsManage.get('groups')?.groups!;
          const groupsData = groupsAllData.get(payload.oldGroup);
          if (groupsData?.isRequest && groupsData.friends.size)
            for (const item of groupsData!.friends!.values()) item.group = payload.newGroup;
          const groupsAllDataArr = [...groupsAllData];
          const index: number = groupsAllDataArr.findIndex(item => item[0] === payload.oldGroup);
          groupsAllDataArr[index][0] = payload.newGroup;
          this.friendsManage.get('groups')!.groups = new Map(groupsAllDataArr);
        },
      )
    },
    // 删除分组
    async deleteGroup(payload: {
      selfId: string;
      group: string;
      isNeed?: boolean;
    }): Promise<number> {
      return await $axios(
        ['/friend/group/deleteGroup', 'delete', payload],
        ({ otherIds, userInfos }) => {
          if (this.groups.value.includes(payload.group)) {
            const index: number = this.groups.value.findIndex(item => item === payload.group);
            this.groups.value.splice(index, 1);
          }
          const groupAllData = this.friendsManage.get('groups')?.groups!;
          const groupData = groupAllData.get(payload.group);
          const noGroupData = groupAllData.get('无分组');
          const count: number = groupData?.count!;
          if (!payload.isNeed && groupData?.isRequest && noGroupData?.isRequest)
            for (const [key, value] of groupData.friends.entries()) {
              value.group = '';
              noGroupData.friends.set(key, value)
            }
          groupAllData.delete(payload.group);
          noGroupData ? noGroupData.count += count : undefined;
          if (otherIds.length) {
            for (let i = 0; i < otherIds.length; i++) {
              payload.isNeed && noGroupData?.friends.set(otherIds[i], userInfos[i]);

              const cacheInfo = this.friendsInfos.get(otherIds[i]);
              cacheInfo ? cacheInfo.group = '' : undefined;

              const strs = ['all', 'disabledOtherLook', 'disabledSelfLook'] as const;
              for (const str of strs) {
                const friendsData = this.friendsManage.get(str)?.noGroups;
                if (friendsData?.isRequest && friendsData.friends.has(otherIds[i]))
                  friendsData.friends.get(otherIds[i])!.group = '';
              }
            }
          }
        },
      )
    },
    // 向分组里面添加成员
    async addFriFromGroup(payload: {
      selfId: string;
      otherIds: Array<string>;
      group: string;
      isNeed?: boolean;
    }): Promise<number> {
      return await $axios(
        ['/friend/group/addFriFromGroup', 'patch', payload],
        ({ userInfos }) => {
          const noGroupData = this.friendsManage.get('groups')?.groups!.get('无分组');
          const idsLen: number = payload.otherIds.length
          noGroupData ? noGroupData.count -= idsLen : undefined;
          const groupData = this.friendsManage.get('groups')?.groups?.get(payload.group)!;
          groupData.count += idsLen;
          for (let i = 0; i < idsLen; i++) {
            noGroupData?.isRequest && noGroupData.friends.delete(payload.otherIds[i]);
            const cacheInfo = this.friendsInfos.get(payload.otherIds[i]);
            cacheInfo ? cacheInfo.group = payload.group : undefined;

            const strs = ['all', 'disabledOtherLook', 'disabledSelfLook'] as const;
            for (const str of strs) {
              const friendsData = this.friendsManage.get(str)?.noGroups;
              if (friendsData?.isRequest && friendsData.friends.has(payload.otherIds[i]))
                friendsData.friends.get(payload.otherIds[i])!.group = payload.group;
            }
            payload.isNeed && groupData.friends.set(payload.otherIds[i], userInfos[i]);
          }
        },
      )
    },
    // 搜索好友
    searchFriend(payload: { keyword: string }): Promise<{
      code: number;
      friendsData: Array<Pick<OtherIdInfo, 'userId' | 'avatar' | 'remark'> &
      { initials: string }
      >;
    }> {
      let friendsData: Array<Pick<OtherIdInfo, 'userId' | 'avatar' | 'remark'> & { initials: string }>;
      return new Promise<{
        code: number;
        friendsData: Array<Pick<OtherIdInfo, 'userId' | 'avatar' | 'remark'> &
        { initials: string }
        >;
      }>((resolve, reject) => {
        $axios(
          ['/friend/searchFriend', 'get', payload],
          (data) => friendsData = data
        ).then(code => resolve({ code, friendsData })).catch(() => reject());
      })
    },
  },
})